package com.dpp.dbase.utils;

import android.graphics.Color;
import android.util.Log;

import com.dpp.dbase.config.LayerStyleConfig;
import com.dpp.dbase.config.SymbolConfig;
import com.esri.arcgisruntime.data.Field;
import com.esri.arcgisruntime.data.GeoPackage;
import com.esri.arcgisruntime.data.GeoPackageFeatureTable;
import com.esri.arcgisruntime.layers.FeatureLayer;
import com.esri.arcgisruntime.loadable.LoadStatus;
import com.esri.arcgisruntime.symbology.Renderer;
import com.esri.arcgisruntime.symbology.SimpleFillSymbol;
import com.esri.arcgisruntime.symbology.SimpleLineSymbol;
import com.esri.arcgisruntime.symbology.SimpleMarkerSymbol;
import com.esri.arcgisruntime.symbology.SimpleRenderer;
import com.esri.arcgisruntime.symbology.Symbol;
import com.esri.arcgisruntime.symbology.UniqueValueRenderer;

import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
/**
 * 分类样式配置类
 */
public class GpkgManager {
    private static GpkgManager instance;
    private GeoPackage currentGeoPackage;
    private Map<String, GeoPackageFeatureTable> featureTables = new HashMap<>();
    private Map<String, FeatureLayer> featureLayers = new HashMap<>();
    private Map<String, Renderer> layerRenderers = new HashMap<>();
    private Map<String, LayerStyleConfig> layerStyleConfigs = new HashMap<>();

    // 图层类型常量
    public static final String LAYER_POINT = "point";
    public static final String LAYER_POLYLINE = "polyline";
    public static final String LAYER_POLYGON = "polygon";

    // 符号样式常量
    public static final String SYMBOL_CIRCLE = "CIRCLE";
    public static final String SYMBOL_TRIANGLE = "TRIANGLE";
    public static final String SYMBOL_SQUARE = "SQUARE";
    public static final String SYMBOL_CROSS = "CROSS";
    public static final String SYMBOL_X = "X";
    public static final String SYMBOL_DIAMOND = "DIAMOND";

    public interface GpkgLoadListener {
        void onLoadSuccess(Map<String, FeatureLayer> layers);

        void onLoadFailure(String error);
    }

    private GpkgManager() {
    }

    public static synchronized GpkgManager getInstance() {
        if (instance == null) {
            instance = new GpkgManager();
        }
        return instance;
    }

    /**
     * 设置图层样式配置
     */
    public void setLayerStyleConfig(String layerName, LayerStyleConfig styleConfig) {
        layerStyleConfigs.put(layerName, styleConfig);

        // 如果图层已经存在，立即应用新样式
        FeatureLayer layer = featureLayers.get(layerName);
        if (layer != null) {
            applyLayerStyle(layerName, layer);
        }
    }

    /**
     * 获取图层样式配置
     */
    public LayerStyleConfig getLayerStyleConfig(String layerName) {
        return layerStyleConfigs.get(layerName);
    }

    /**
     * 移除图层样式配置
     */
    public void removeLayerStyleConfig(String layerName) {
        layerStyleConfigs.remove(layerName);
    }

    /**
     * 加载 GPKG 文件（支持样式配置）
     */
    public void loadGeoPackage(String gpkgPath, Map<String, String> filterConditions,
                               Map<String, LayerStyleConfig> styleConfigs, GpkgLoadListener listener) {
        try {
            clearResources();

            // 存储样式配置
            if (styleConfigs != null) {
                layerStyleConfigs.putAll(styleConfigs);
            }

            currentGeoPackage = new GeoPackage(gpkgPath);
            currentGeoPackage.loadAsync();
            currentGeoPackage.addDoneLoadingListener(() -> {
                if (currentGeoPackage.getLoadStatus() == LoadStatus.LOADED) {
                    setupFeatureLayers(listener, filterConditions);
                } else {
                    listener.onLoadFailure("GPKG加载失败: " + currentGeoPackage.getLoadError().getMessage());
                }
            });
        } catch (Exception e) {
            listener.onLoadFailure("GPKG初始化失败: " + e.getMessage());
        }
    }

    /**
     * 设置要素图层
     */
    private void setupFeatureLayers(GpkgLoadListener listener, Map<String, String> filterConditions) {
        List<GeoPackageFeatureTable> tables = currentGeoPackage.getGeoPackageFeatureTables();
        if (tables == null || tables.isEmpty()) {
            listener.onLoadFailure("GPKG中没有要素表");
            return;
        }

        for (GeoPackageFeatureTable table : tables) {
            String tableName = table.getTableName();

            FeatureLayer featureLayer = new FeatureLayer(table);

            // 设置查询过滤条件
            if (filterConditions != null && filterConditions.containsKey(tableName)) {
                String whereClause = filterConditions.get(tableName);
                if (whereClause != null && !whereClause.isEmpty()) {
                    try {
                        featureLayer.setDefinitionExpression(whereClause);
                        Log.i("GpkgManager", "为图层 " + tableName + " 设置过滤条件: " + whereClause);
                    } catch (Exception e) {
                        Log.e("GpkgManager", "设置过滤条件失败: " + e.getMessage());
                    }
                }
            }

            // 存储到管理器中
            featureTables.put(tableName, table);
            featureLayers.put(tableName, featureLayer);

            // 配置图层样式（支持动态配置）
            configureLayerStyle(tableName, featureLayer);

            Log.i("GpkgManager", "加载图层: " + tableName);
        }

        listener.onLoadSuccess(new HashMap<>(featureLayers));
    }

    /**
     * 配置图层样式（支持动态配置）
     */
    private void configureLayerStyle(String tableName, FeatureLayer layer) {
        try {
            // 优先使用外部配置的样式
            if (layerStyleConfigs.containsKey(tableName)) {
                applyLayerStyle(tableName, layer);
                return;
            }

            // 如果没有外部配置，尝试自动检测合适的字段进行唯一值渲染
            GeoPackageFeatureTable table = featureTables.get(tableName);
            if (table == null) return;

            List<Field> fields = table.getFields();
            String styleField = detectStyleField(fields, tableName);

            Renderer renderer;

            if (styleField != null) {
                // 自动创建基于检测字段的唯一值渲染器
                Map<String, SymbolConfig> autoValueMap = createAutoValueMap(tableName, styleField);
                renderer = createUniqueValueRenderer(tableName, styleField, autoValueMap);
            } else {
                // 使用简单渲染器
                renderer = createSimpleRenderer(tableName);
            }

            layer.setRenderer(renderer);
            layerRenderers.put(tableName, renderer);

            Log.i("GpkgManager", "为图层 " + tableName + " 设置样式，使用字段: " + styleField);

        } catch (Exception e) {
            Log.e("GpkgManager", "配置图层样式失败: " + e.getMessage());
            layer.setRenderer(createSimpleRenderer(tableName));
        }
    }

    /**
     * 应用图层样式
     */
    private void applyLayerStyle(String tableName, FeatureLayer layer) {
        try {
            LayerStyleConfig styleConfig = layerStyleConfigs.get(tableName);
            if (styleConfig == null) return;

            Renderer renderer;

            if (styleConfig.getStyleField() != null && !styleConfig.getValueSymbols().isEmpty()) {
                // 使用唯一值渲染器
                renderer = createUniqueValueRenderer(tableName, styleConfig.getStyleField(), styleConfig.getValueSymbols());
            } else if (styleConfig.getDefaultSymbol() != null) {
                // 使用简单渲染器
                renderer = createDynamicSimpleRenderer(tableName, styleConfig.getDefaultSymbol());
            } else {
                // 回退到默认样式
                renderer = createSimpleRenderer(tableName);
            }

            layer.setRenderer(renderer);
            layerRenderers.put(tableName, renderer);

            Log.i("GpkgManager", "为图层 " + tableName + " 应用动态样式配置");

        } catch (Exception e) {
            Log.e("GpkgManager", "应用动态样式失败: " + e.getMessage());
            layer.setRenderer(createSimpleRenderer(tableName));
        }
    }

    /**
     * 创建唯一值渲染器 - 支持动态字段和值配置
     */
    private UniqueValueRenderer createUniqueValueRenderer(String tableName, String fieldName, Map<String, SymbolConfig> valueSymbolMap) {
        UniqueValueRenderer renderer = new UniqueValueRenderer();
        renderer.getFieldNames().add(fieldName);

        // 为每个字段值创建对应的符号
        for (Map.Entry<String, SymbolConfig> entry : valueSymbolMap.entrySet()) {
            String fieldValue = entry.getKey();
            SymbolConfig symbolConfig = entry.getValue();

            Symbol symbol = createSymbolFromConfig(tableName, symbolConfig);
            if (symbol != null) {
                renderer.getUniqueValues().add(new UniqueValueRenderer.UniqueValue(
                        fieldValue, // 显示标签
                        fieldValue, // 描述
                        symbol,
                        Collections.singletonList(fieldValue)
                ));
            }
        }

        // 设置默认符号（用于没有匹配值的要素）
        SymbolConfig defaultConfig = valueSymbolMap.get("default");
        if (defaultConfig != null) {
            renderer.setDefaultSymbol(createSymbolFromConfig(tableName, defaultConfig));
        } else {
            // 如果没有指定默认符号，使用第一个符号或创建灰色默认符号
            if (!valueSymbolMap.isEmpty()) {
                SymbolConfig firstConfig = valueSymbolMap.values().iterator().next();
                renderer.setDefaultSymbol(createSymbolFromConfig(tableName, firstConfig));
            } else {
                renderer.setDefaultSymbol(createDefaultSymbol(tableName));
            }
        }

        return renderer;
    }

    /**
     * 创建基于状态字段的唯一值渲染器
     * 例如：upload字段：0=红色，1=蓝色，2=绿色
     */
    public void createStatusBasedRenderer(String tableName, String statusField,
                                          Map<Integer, Integer> statusColorMap) {
        Map<String, SymbolConfig> valueSymbolMap = new HashMap<>();

        for (Map.Entry<Integer, Integer> entry : statusColorMap.entrySet()) {
            String fieldValue = String.valueOf(entry.getKey());
            int color = entry.getValue();

            SymbolConfig symbolConfig = createSymbolConfigByTableType(tableName, color);
            valueSymbolMap.put(fieldValue, symbolConfig);
        }

        // 应用渲染器
        applyUniqueValueRenderer(tableName, statusField, valueSymbolMap);
    }

    /**
     * 创建基于分类字段的唯一值渲染器
     * 例如：type字段：不同的类型对应不同的颜色和符号
     */
    public void createCategoryBasedRenderer(String tableName, String categoryField,
                                            Map<String, CategoryStyle> categoryStyleMap) {
        Map<String, SymbolConfig> valueSymbolMap = new HashMap<>();

        for (Map.Entry<String, CategoryStyle> entry : categoryStyleMap.entrySet()) {
            String categoryValue = entry.getKey();
            CategoryStyle style = entry.getValue();

            SymbolConfig symbolConfig = new SymbolConfig(style.getSymbolType(), style.getColor());
            symbolConfig.setSize(style.getSize());
            symbolConfig.setStyle(style.getSymbolStyle());
            symbolConfig.setAlpha(style.getAlpha());

            if (style.getOutlineColor() != 0) {
                symbolConfig.setOutlineColor(style.getOutlineColor());
                symbolConfig.setOutlineWidth(style.getOutlineWidth());
            }

            valueSymbolMap.put(categoryValue, symbolConfig);
        }

        // 应用渲染器
        applyUniqueValueRenderer(tableName, categoryField, valueSymbolMap);
    }

    /**
     * 应用唯一值渲染器到指定图层
     */
    private void applyUniqueValueRenderer(String tableName, String fieldName, Map<String, SymbolConfig> valueSymbolMap) {
        FeatureLayer layer = featureLayers.get(tableName);
        if (layer != null) {
            UniqueValueRenderer renderer = createUniqueValueRenderer(tableName, fieldName, valueSymbolMap);
            layer.setRenderer(renderer);
            layerRenderers.put(tableName, renderer);
            Log.i("GpkgManager", "为图层 " + tableName + " 应用唯一值渲染器，字段: " + fieldName);
        }
    }

    /**
     * 根据配置创建符号（动态适配图层几何类型）
     */
    private Symbol createSymbolFromConfig(String tableName, SymbolConfig config) {
        if (config == null) return createDefaultSymbol(tableName);

        // 首先根据配置的符号类型创建
        Symbol symbol = createSymbolByType(config);
        if (symbol != null) {
            return symbol;
        }

        // 如果配置中没有指定符号类型，则根据表名或图层类型推断
        return createSymbolByLayerType(tableName, config);
    }

    /**
     * 根据配置的符号类型创建符号
     */
    private Symbol createSymbolByType(SymbolConfig config) {
        if (config.getSymbolType() == null) return null;

        switch (config.getSymbolType()) {
            case "point":
            case "points":
                SimpleMarkerSymbol.Style markerStyle = getMarkerStyle(config.getStyle());
                int pointColor = applyAlpha(config.getColor(), config.getAlpha());
                return new SimpleMarkerSymbol(markerStyle, pointColor, config.getSize());

            case "line":
            case "polyline":
            case "lines":
                int lineColor = applyAlpha(config.getColor(), config.getAlpha());
                return new SimpleLineSymbol(SimpleLineSymbol.Style.SOLID, lineColor, config.getSize());

            case "polygon":
            case "polygons":
            case "fill":
                int fillColor = applyAlpha(config.getColor(), config.getAlpha());
                SimpleLineSymbol outline = createLineSymbol(
                        config.getOutlineColor() != 0 ? config.getOutlineColor() : Color.BLACK,
                        config.getOutlineWidth() > 0 ? config.getOutlineWidth() : 1
                );
                return new SimpleFillSymbol(SimpleFillSymbol.Style.SOLID, fillColor, outline);

            default:
                return null;
        }
    }

    /**
     * 根据图层类型推断并创建符号
     */
    private Symbol createSymbolByLayerType(String tableName, SymbolConfig config) {
        // 获取图层的几何类型
        String geometryType = detectGeometryType(tableName);

        int color = config.getColor() != 0 ? config.getColor() : Color.GRAY;
        int size = config.getSize() > 0 ? config.getSize() : 12;
        int alpha = config.getAlpha() > 0 ? config.getAlpha() : 255;

        switch (geometryType) {
            case "point":
            case "multipoint":
                SimpleMarkerSymbol.Style markerStyle = getMarkerStyle(config.getStyle());
                int pointColor = applyAlpha(color, alpha);
                return new SimpleMarkerSymbol(markerStyle, pointColor, size);

            case "line":
            case "polyline":
            case "multiline":
                int lineColor = applyAlpha(color, alpha);
                return new SimpleLineSymbol(SimpleLineSymbol.Style.SOLID, lineColor, size);

            case "polygon":
            case "multipolygon":
                int fillColor = applyAlpha(color, alpha);
                SimpleLineSymbol outline = createLineSymbol(
                        config.getOutlineColor() != 0 ? config.getOutlineColor() : Color.BLACK,
                        config.getOutlineWidth() > 0 ? config.getOutlineWidth() : 1
                );
                return new SimpleFillSymbol(SimpleFillSymbol.Style.SOLID, fillColor, outline);

            default:
                // 默认创建点符号
                return createPointSymbol(color, size);
        }
    }

    /**
     * 检测图层的几何类型
     */
    private String detectGeometryType(String tableName) {
        GeoPackageFeatureTable table = featureTables.get(tableName);
        if (table == null) return "point";

        try {
            String geometryType = table.getGeometryType().name().toLowerCase();

            // 映射到通用类型
            if (geometryType.contains("point")) {
                return "point";
            } else if (geometryType.contains("line") || geometryType.contains("linestring")) {
                return "line";
            } else if (geometryType.contains("polygon")) {
                return "polygon";
            } else {
                return geometryType;
            }
        } catch (Exception e) {
            Log.e("GpkgManager", "检测几何类型失败: " + e.getMessage());

            // 根据表名推断
            if (tableName.toLowerCase().contains("point") ||
                    tableName.toLowerCase().contains("station") ||
                    tableName.toLowerCase().contains("location")) {
                return "point";
            } else if (tableName.toLowerCase().contains("line") ||
                    tableName.toLowerCase().contains("track") ||
                    tableName.toLowerCase().contains("road")) {
                return "line";
            } else if (tableName.toLowerCase().contains("polygon") ||
                    tableName.toLowerCase().contains("area") ||
                    tableName.toLowerCase().contains("region")) {
                return "polygon";
            } else {
                return "point"; // 默认
            }
        }
    }

    /**
     * 获取点符号样式
     */
    private SimpleMarkerSymbol.Style getMarkerStyle(String style) {
        if (style == null) return SimpleMarkerSymbol.Style.CIRCLE;

        switch (style.toUpperCase()) {
            case "TRIANGLE":
                return SimpleMarkerSymbol.Style.TRIANGLE;
            case "SQUARE":
                return SimpleMarkerSymbol.Style.SQUARE;
            case "CROSS":
                return SimpleMarkerSymbol.Style.CROSS;
            case "X":
                return SimpleMarkerSymbol.Style.X;
            case "DIAMOND":
                return SimpleMarkerSymbol.Style.DIAMOND;
            case "CIRCLE":
            default:
                return SimpleMarkerSymbol.Style.CIRCLE;
        }
    }

    /**
     * 应用透明度
     */
    private int applyAlpha(int color, int alpha) {
        return Color.argb(alpha, Color.red(color), Color.green(color), Color.blue(color));
    }

    /**
     * 根据表类型创建符号配置
     */
    private SymbolConfig createSymbolConfigByTableType(String tableName, int color) {
        String geometryType = detectGeometryType(tableName);

        SymbolConfig config = new SymbolConfig(geometryType, color);

        switch (geometryType) {
            case "point":
                config.setSize(10);
                config.setStyle("CIRCLE");
                break;
            case "line":
                config.setSize(2);
                break;
            case "polygon":
                config.setAlpha(150);
                config.setOutlineColor(Color.BLACK);
                config.setOutlineWidth(1);
                break;
        }

        return config;
    }

    /**
     * 为检测到的字段自动创建值-符号映射
     */
    private Map<String, SymbolConfig> createAutoValueMap(String tableName, String fieldName) {
        Map<String, SymbolConfig> valueMap = new HashMap<>();

        // 这里可以根据字段名和表名推测可能的取值和对应的样式
        if (fieldName.toLowerCase().contains("status") || fieldName.toLowerCase().contains("state")) {
            // 状态字段
            valueMap.put("0", createSymbolConfigByTableType(tableName, Color.RED));
            valueMap.put("1", createSymbolConfigByTableType(tableName, Color.YELLOW));
            valueMap.put("2", createSymbolConfigByTableType(tableName, Color.GREEN));
            valueMap.put("default", createSymbolConfigByTableType(tableName, Color.GRAY));
        } else if (fieldName.toLowerCase().contains("type") || fieldName.toLowerCase().contains("category")) {
            // 类型字段
            int[] colors = {Color.RED, Color.BLUE, Color.GREEN, Color.YELLOW, Color.CYAN, Color.MAGENTA};
            for (int i = 0; i < colors.length; i++) {
                valueMap.put(String.valueOf(i), createSymbolConfigByTableType(tableName, colors[i]));
            }
            valueMap.put("default", createSymbolConfigByTableType(tableName, Color.GRAY));
        } else {
            // 其他字段，创建几个默认样式
            valueMap.put("default", createSymbolConfigByTableType(tableName, Color.BLUE));
        }

        return valueMap;
    }

    /**
     * 创建动态简单渲染器
     */
    private SimpleRenderer createDynamicSimpleRenderer(String tableName, SymbolConfig symbolConfig) {
        Symbol symbol = createSymbolFromConfig(tableName, symbolConfig);
        return new SimpleRenderer(symbol != null ? symbol : createDefaultSymbol(tableName));
    }

    private SimpleRenderer createSimpleRenderer(String tableName) {
        Symbol symbol = createDefaultSymbol(tableName);
        return new SimpleRenderer(symbol);
    }

    private SimpleMarkerSymbol createPointSymbol(int color, int size) {
        return new SimpleMarkerSymbol(SimpleMarkerSymbol.Style.CIRCLE, color, size);
    }

    private SimpleMarkerSymbol createTRIANGLEPointSymbol(int color, int size) {
        return new SimpleMarkerSymbol(SimpleMarkerSymbol.Style.TRIANGLE, color, size);
    }

    private SimpleLineSymbol createLineSymbol(int color, float width) {
        return new SimpleLineSymbol(SimpleLineSymbol.Style.SOLID, color, width);
    }

    private SimpleFillSymbol createPolygonSymbol(int color, int alpha) {
        int fillColor = Color.argb(alpha, Color.red(color), Color.green(color), Color.blue(color));
        return new SimpleFillSymbol(SimpleFillSymbol.Style.SOLID, fillColor,
                createLineSymbol(Color.RED, 1));
    }

    private Symbol createDefaultSymbol(String tableName) {
        switch (tableName) {
            case "warehouse":
            case "cooperative":
            case "tobacco_station":
            case "location_point":
                return createPointSymbol(Color.RED, 12);
            case "record_point":
                return createTRIANGLEPointSymbol(Color.RED, 0);
            case LAYER_POLYLINE:
            case "record_track":
                return createLineSymbol(Color.YELLOW, 3);
            case "yttk_hn":
            case "location_polygon":
                return createPolygonSymbol(Color.RED, 50);
            default:
                return createPointSymbol(Color.GRAY, 12);
        }
    }

    /**
     * 为图层设置统一颜色样式
     * @param layerName 图层名称
     * @param color 颜色值（如 Color.RED）
     * @param size 符号大小（点：直径，线：宽度）
     */
    public void setLayerSimpleStyle(String layerName, int color, int size) {
        SymbolConfig symbolConfig = createSymbolConfigByTableType(layerName, color);
        symbolConfig.setSize(size);

        LayerStyleConfig styleConfig = new LayerStyleConfig(layerName);
        styleConfig.setDefaultSymbol(symbolConfig);

        setLayerStyleConfig(layerName, styleConfig);
    }

    /**
     * 为图层设置统一颜色样式（带透明度）
     * @param layerName 图层名称
     * @param color 颜色值
     * @param size 符号大小
     * @param alpha 透明度 (0-255)
     */
    public void setLayerSimpleStyle(String layerName, int color, int size, int alpha) {
        SymbolConfig symbolConfig = createSymbolConfigByTableType(layerName, color);
        symbolConfig.setSize(size);
        symbolConfig.setAlpha(alpha);

        LayerStyleConfig styleConfig = new LayerStyleConfig(layerName);
        styleConfig.setDefaultSymbol(symbolConfig);

        setLayerStyleConfig(layerName, styleConfig);
    }

    /**
     * 为图层设置自定义符号配置
     * @param layerName 图层名称
     * @param symbolConfig 符号配置
     */
    public void setLayerSimpleStyle(String layerName, SymbolConfig symbolConfig) {
        LayerStyleConfig styleConfig = new LayerStyleConfig(layerName);
        styleConfig.setDefaultSymbol(symbolConfig);
        setLayerStyleConfig(layerName, styleConfig);
    }
    /**
     * 批量设置多个图层的简单样式
     * @param layerStyles 图层样式映射表
     */
    public void setMultipleLayersSimpleStyle(Map<String, SimpleStyleConfig> layerStyles) {
        for (Map.Entry<String, SimpleStyleConfig> entry : layerStyles.entrySet()) {
            String layerName = entry.getKey();
            SimpleStyleConfig styleConfig = entry.getValue();

            setLayerSimpleStyle(layerName, styleConfig.getColor(),
                    styleConfig.getSize(), styleConfig.getAlpha());
        }
    }

    private String detectStyleField(List<Field> fields, String tableName) {
        Set<String> commonStyleFields = new HashSet<>(Arrays.asList(
                "type", "category", "class", "level", "status", "landuse", "road_type"
        ));

        for (Field field : fields) {
            if (commonStyleFields.contains(field.getName().toLowerCase())) {
                return field.getName();
            }
        }

        // 表特定的字段
        switch (tableName) {
            case LAYER_POINT:
                return findFieldByName(fields, Arrays.asList("point_type", "sample_type"));
            case LAYER_POLYLINE:
                return findFieldByName(fields, Arrays.asList("line_type", "road_type"));
            case LAYER_POLYGON:
                return findFieldByName(fields, Arrays.asList("polygon_type", "landuse"));
            default:
                return null;
        }
    }

    private String findFieldByName(List<Field> fields, List<String> possibleNames) {
        for (String name : possibleNames) {
            for (Field field : fields) {
                if (name.equalsIgnoreCase(field.getName())) {
                    return field.getName();
                }
            }
        }
        return null;
    }

    /**
     * 获取指定图层
     */
    public FeatureLayer getFeatureLayer(String layerName) {
        return featureLayers.get(layerName);
    }

    /**
     * 获取所有图层
     */
    public Map<String, FeatureLayer> getAllFeatureLayers() {
        return new HashMap<>(featureLayers);
    }

    /**
     * 获取要素表
     */
    public GeoPackageFeatureTable getFeatureTable(String tableName) {
        return featureTables.get(tableName);
    }

    /**
     * 设置图层定义表达式（过滤条件）
     */
    public void setLayerDefinitionExpression(String layerName, String definitionExpression) {
        try {
            FeatureLayer layer = featureLayers.get(layerName);
            if (layer != null) {
                layer.setDefinitionExpression(definitionExpression);
                Log.i("GpkgManager", "更新图层 " + layerName + " 过滤条件: " + definitionExpression);
            }
        } catch (Exception e) {
            Log.e("GpkgManager", "设置图层过滤条件失败: " + e.getMessage());
        }
    }

    /**
     * 清除图层过滤条件
     */
    public void clearLayerDefinitionExpression(String layerName) {
        setLayerDefinitionExpression(layerName, "");
    }

    /**
     * 获取图层的当前定义表达式
     */
    public String getLayerDefinitionExpression(String layerName) {
        FeatureLayer layer = featureLayers.get(layerName);
        return layer != null ? layer.getDefinitionExpression() : "";
    }

    /**
     * 清除资源
     */
    public void clearResources() {
        if (currentGeoPackage != null) {
            currentGeoPackage.close();
        }
        featureTables.clear();
        featureLayers.clear();
        layerRenderers.clear();
        layerStyleConfigs.clear();
    }

    public static class CategoryStyle {
        private String symbolType;
        private int color;
        private int size;
        private String symbolStyle;
        private int alpha = 255;
        private int outlineColor;
        private float outlineWidth = 1;

        public CategoryStyle(String symbolType, int color) {
            this.symbolType = symbolType;
            this.color = color;
        }

        // Getters and Setters
        public String getSymbolType() { return symbolType; }
        public void setSymbolType(String symbolType) { this.symbolType = symbolType; }

        public int getColor() { return color; }
        public void setColor(int color) { this.color = color; }

        public int getSize() { return size; }
        public void setSize(int size) { this.size = size; }

        public String getSymbolStyle() { return symbolStyle; }
        public void setSymbolStyle(String symbolStyle) { this.symbolStyle = symbolStyle; }

        public int getAlpha() { return alpha; }
        public void setAlpha(int alpha) { this.alpha = alpha; }

        public int getOutlineColor() { return outlineColor; }
        public void setOutlineColor(int outlineColor) { this.outlineColor = outlineColor; }

        public float getOutlineWidth() { return outlineWidth; }
        public void setOutlineWidth(float outlineWidth) { this.outlineWidth = outlineWidth; }
    }

    /**
     * 简单样式配置类（用于批量设置）
     */
    public static class SimpleStyleConfig {
        private int color;
        private int size;
        private int alpha = 255;

        public SimpleStyleConfig(int color, int size) {
            this.color = color;
            this.size = size;
        }

        public SimpleStyleConfig(int color, int size, int alpha) {
            this.color = color;
            this.size = size;
            this.alpha = alpha;
        }

        // Getters
        public int getColor() { return color; }
        public int getSize() { return size; }
        public int getAlpha() { return alpha; }
    }

}
